package ch.cm.adnroid.cleverlearn.load;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import ch.cm.adnroid.cleverlearn.R;
import ch.cm.adnroid.cleverlearn.R.id;
import ch.cm.adnroid.cleverlearn.load.util.CLFileValidator;
import ch.cm.adnroid.cleverlearn.model.DatabaseManager;

public class CleverLearnLoad extends ListActivity {

    private static final int EMPTY_CURSOR = 0;
    public static final String DIRECTORY = "cleverLearn";
    public static final String LOCATION = "/sdcard/";

    private DatabaseManager databaseManager;
    private SQLiteDatabase database;

    private File file;
    private Button validateButton, loadButton, appendButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clever_learn_load);

        validateButton = (Button) findViewById(R.id.bu_load_validate);
        loadButton = (Button) findViewById(R.id.bu_load_load);
        appendButton = (Button) findViewById(R.id.bu_load_append);

        databaseManager = new DatabaseManager(this);

    }

    public void onButtonClick(View view) {
        switch (view.getId()) {
        case R.id.bu_load_validate:
            if (new CLFileValidator().validateFile(file)) {
                loadButton.setEnabled(true);
                if (tableAlreadyexists(file)) {
                    appendButton.setEnabled(true);
                }
            } else {
                Toast.makeText(this, getResources().getString(R.string.toast_load_filenotvalid), Toast.LENGTH_SHORT)
                        .show();
                loadButton.setEnabled(false);
                appendButton.setEnabled(false);
            }
            break;
        case R.id.bu_load_load:
            if (file != null && database != null) {
                new CLFileValidator().saveInDB(database, file, this);
                loadButton.setEnabled(false);
                appendButton.setEnabled(false);
            }
            break;
        case id.bu_load_append:
            if (file != null && database != null) {
                new CLFileValidator().appendInDB(database, file, this);
                loadButton.setEnabled(false);
                appendButton.setEnabled(false);
            }
            break;

        }
    }

    private boolean tableAlreadyexists(File file) {
        try {
            String tableName = new CLFileValidator().getTableName(file);
            Cursor cursor = database.query(tableName, DatabaseManager.getAllTableColumns(), null, null, null, null,
                    null);
            if (cursor.getCount() != EMPTY_CURSOR) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        database.close();
    }

    @Override
    protected void onResume() {
        super.onResume();
        database = databaseManager.getReadableDatabase();
        fillList();
        addClicklistenertoList();

    }

    private void addClicklistenertoList() {

        getListView().setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                loadButton.setEnabled(false);
                appendButton.setEnabled(false);
                TextView tv = (TextView) arg1;
                file = new File(LOCATION + DIRECTORY + "/" + tv.getText());
                if (file != null) {
                    validateButton.setEnabled(true);
                    validateButton.setText(file.getName() + " " + getResources().getString(R.string.bu_load_validate));
                }
            }

        });
    }

    private void fillList() {
        List<String> list = getAllFileNames();
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
        setListAdapter(arrayAdapter);

    }

    private List<String> getAllFileNames() {
        List<String> list = new ArrayList<String>();
        File dir = new File(LOCATION + DIRECTORY);
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (int i = 0; i < files.length; i++) {
                list.add(files[i].getName());
            }
        }
        return list;
    }

}
